package com.vf.admin.client.controller;

import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.service.AppMingXiZuanShiService;
import com.vf.admin.client.service.AppMingxiFreetimeService;
import com.vf.admin.client.service.AppSetupService;
import com.vf.admin.client.service.AppUserService;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.miaodong.entity.AppUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

import static com.vf.admin.common.Constants.SEX_STATE_NAN;
import static com.vf.admin.utils.StringEx.isNull;

/**
 * @Description 一对一视频接口
 * @createTime 2021年07月30日 15:15:00
 */
@Controller
@RequestMapping("/app/yiduiyishipin")
public class AppYiDuiYiShiPinController extends ClientBaseController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppSetupService appSetupService;
    @Autowired
    AppMingXiZuanShiService appMingXiZuanShiService;
    @Autowired
    AppMingxiFreetimeService appMingxiFreetimeService;

    //初始化公平锁
    ReentrantLock lock = new ReentrantLock(true);

    /**
     * @Description 发起or取消 一对一视频
     * @Param: leixing 1发起匹配 2取消匹配
     * @Date: 2021/07/30
     */
    @ResponseBody
    @RequestMapping("/action")
    public Result action(Integer leixing, Integer type) {
        lock.lock();
        try {

            if (leixing == null) {
                return this.errorJSON("操作类型为空");
            }

            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            if (user.getSex() == null) {
                return this.errorJSON("用户性别为空,不可匹配");
            }

            String key = "voiceMatch", sex = "1";
            if (type == 1) {
                key = "voiceMatch";
            } else if (type == 2) {
                key = "videoMatch";
            }
            //发起匹配
            if (leixing.intValue() == 1) {
                if (user.getSex() == SEX_STATE_NAN) {
                    sex = "2";
                    //当用户的性别是男
                    //先查询redis是否存在带匹配的异性
                    Map<Object, Object> map = redisUtil.hmget(key + sex);
                    List<String> list = new ArrayList<>();
                    for (Map.Entry<Object, Object> entry : map.entrySet()) {
                        Object mapKey = entry.getKey();
                        Object mapValue = entry.getValue();
                        System.out.println(mapKey + ":" + mapValue);
                        list.add(mapKey.toString());
                    }
                    if (list.size() > 0) {
                        Random random = new Random();
                        int index = random.nextInt(list.size());
                        String userid = list.get(index);
                        redisUtil.hdel(key + sex, userid);
                        return sucessJSON(userid, "匹配成功");
                    } else {
                        redisUtil.hset(key + "1", user.getTengxuncode() + "", System.currentTimeMillis() + "");
                        return errorCLJSON("正在匹配中");
                    }
                } else {
                    sex = "1";
                    //当用户的性别是女
                    //先查询redis是否存在带匹配的异性
                    Map<Object, Object> map = redisUtil.hmget(key + sex);
                    List<String> list = new ArrayList<>();
                    for (Map.Entry<Object, Object> entry : map.entrySet()) {
                        Object mapKey = entry.getKey();
                        Object mapValue = entry.getValue();
                        System.out.println(mapKey + ":" + mapValue);
                        list.add(mapKey.toString());
                    }
                    if (list.size() > 0) {
                        Random random = new Random();
                        int index = random.nextInt(list.size());
                        String userid = list.get(index);
                        redisUtil.hdel(key + sex, userid);
                        return sucessJSON(userid, "匹配成功");
                    } else {
                        redisUtil.hset(key + "2", user.getTengxuncode() + "", System.currentTimeMillis() + "");
                        return errorCLJSON("正在匹配中");
                    }
                }
            } else {//取消匹配
                if (user.getSex() == SEX_STATE_NAN) {
                    sex = "1";
                    //当用户的性别是男
                    //先查询redis是否存在带匹配的异性
                    redisUtil.hdel(key + sex, user.getTengxuncode() + "");
                } else {
                    sex = "2";
                    //当用户的性别是女
                    //先查询redis是否存在带匹配的异性
                    redisUtil.hdel(key + sex, user.getTengxuncode() + "");
                }
                return sucessJSON("取消匹配成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.logger.debug("发起一对一视频接口异常" + e);
            return this.errorJSON("系统繁忙,请联系管理员！");
        } finally {
            lock.unlock();
        }

    }

    /**
     * @Description 判断用户是否在视频匹配
     * @Date: 2021/07/30
     */
    @ResponseBody
    @RequestMapping("/whetherToMatchInTheVideo")
    public Result whetherToMatchInTheVideo(Integer txCode) {
        try {
            if (isNull(txCode)) {
                return this.errorJSON("腾讯code不能为空");
            }
            //获取当前登录用户的user对象
            AppUser user = appUserService.getTengxuncodeByUser(txCode);
            Map<String, Object> map = new HashMap<>(16);
            if (user.getSex() == SEX_STATE_NAN) {
                //当用户的性别是男
                //先查询redis是否存在带匹配的异性
                boolean flag = redisUtil.hHasKey("videoMatch1", txCode + "");
                if (flag) {
                    map.put("jieguo", 0);
                } else {
                    map.put("jieguo", 1);
                }

            } else {
                //当用户的性别是男
                //先查询redis是否存在带匹配的异性
                boolean flag = redisUtil.hHasKey("videoMatch2", txCode + "");
                if (flag) {
                    map.put("jieguo", 0);
                } else {
                    map.put("jieguo", 1);
                }
            }
            return sucessJSON(map, "查询成功");
        } catch (Exception e) {
            this.logger.debug("发起一对一视频接口异常" + e);
            return this.errorJSON("系统繁忙,请联系管理员！");
        }
    }
}